package com.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.domain.dto.PageDTO;
import com.domain.dto.permission.AddPermissionDTO;
import com.domain.dto.permission.ModifyPermissionDTO;
import com.domain.dto.permission.PermissionDTO;
import com.domain.query.permission.PermissionQuery;
import com.rbac.mapper.PermissionMapper;
import com.rbac.pojo.Permission;
import com.rbac.service.IPermissionService;
import org.mapstruct.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Mapper(componentModel = "spring")
interface msPermissionMapper{
    Permission addPermissionToPermission(AddPermissionDTO addPermissionDTO);
    Permission modifyPermissionToPermission(ModifyPermissionDTO modifyPermissionDTO);
    PermissionDTO PermissionToPermissionDTO(Permission Permission);
}

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    msPermissionMapper msPermissionMapper;

    @Override
    public PageDTO<PermissionDTO> queryPermissionList(PermissionQuery permissionQuery) {
        Page<Permission> page = new Page<>(permissionQuery.getPageIndex(), permissionQuery.getPageSize());
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        if(permissionQuery.getPermissionId() != null){
            wrapper.eq("permission_id",permissionQuery.getPermissionId());
        }
        Page<Permission> result = baseMapper.selectPage(page, wrapper);

        return PageDTO.create(result, msPermissionMapper::PermissionToPermissionDTO);
    }

    @Override
    public PermissionDTO queryPermissionByPermissionId(Integer permissionId) {
        return msPermissionMapper.PermissionToPermissionDTO(baseMapper.selectById(permissionId));
    }

    //添加权限
    @Override
    public Integer addPermission(AddPermissionDTO addPermissionDTO) {
        //将dto数据转换成do数据
        Permission addPermission = msPermissionMapper.addPermissionToPermission(addPermissionDTO);

        //查询父id权限对象（报错： 父节点不存在 (0除外)）
        Permission parentPermission = baseMapper.selectById(addPermission.getParentId());
        if(parentPermission == null) {
            System.out.println("父节点不存在，添加数据失败");
            return null;
        }
        //查询父id子节点的显示顺序，匹配新添加的数据顺序是否重复 （顺延）
        List<Permission> permissionList = baseMapper.selectList(new QueryWrapper<Permission>().eq("parent_id", addPermission.getParentId()));
        int orderNum = 1;
        //TODO 修改添加时，显示的顺序
        for(Permission permission : permissionList){
            if(addPermission.getOrderNum() != null && permission.getOrderNum().equals(addPermission.getOrderNum())){
                System.out.println("显示顺序重复，将顺延显示顺序");
            }else if(!permission.getOrderNum().equals(orderNum)){
                addPermission.setOrderNum(orderNum);
                break;
            }
            orderNum++;
        }

        String menuType = parentPermission.getMenuType();
        //判断父节点是否为0，如果为空，为顶层组件
        if(addPermission.getParentId().equals(0)){
            if(addPermission.getMenuType().equals("F")){
                System.out.println("顶层组件不能是功能");
                return null;
            }
        }else {
            if (menuType == null ) {
                System.out.println("父节点菜单类型错误");
                return null;
            }

            if(menuType.equals("M")){
                if(addPermission.getMenuType().equals("F")){
                    System.out.println("目录不能直接添加功能");
                    return null;
                }
            }else if(menuType.equals("C")){
                if(!addPermission.getMenuType().equals("F")){
                    System.out.println("页面只能添加菜单");
                    return null;
                }
            }
        }
        return baseMapper.insert(addPermission);
    }

    @Override
    public Integer modifyPermission(ModifyPermissionDTO modifyPermissionDTO) {
        //将dto数据转换成do数据
        Permission modifyPermission = msPermissionMapper.modifyPermissionToPermission(modifyPermissionDTO);
        //修改数据并返回修改的行数
        return baseMapper.updateById(modifyPermission);
    }

    @Override
    public Integer removePermission(List<Integer> permissionIds) {
        int totalDeletedRow = 0;
        for(Integer permissionId : permissionIds){
            //删除权限角色中间表数据
            baseMapper.removeRolePermission(permissionId);
            //删除用户数据
            int deletedRow = baseMapper.deleteById(permissionId);
            totalDeletedRow += deletedRow;
        }
        //返回删除的总行数
        return totalDeletedRow;
    }

    //TODO 1、添加角色权限中间表
    public Integer addRolePermission(Integer permissionId, Integer roleId){
        return baseMapper.addRolePermission(permissionId, roleId);
    }

    //TODO 2、查询用户PermissionId对应的角色列表
    public List<String> queryRolePermissionByPermissionId(Integer permissionId){
        return baseMapper.queryRolePermissionByPermissionId(permissionId);
    }

    //TODO 3、删除权限角色中间表数据
    public Integer removeRolePermission(Integer permissionId){
        return baseMapper.removeRolePermission(permissionId);
    }

    //TODO 4、修改用户权限
    public Integer modifyRolePermission(Integer permissionId, List<Integer> roleIds){
        //删除PermissionId用户的全部权限
        int deletedRow = removeRolePermission(permissionId);
        //新增PermissionId的对应权限列表
        int totalAdded = 0;
        for(Integer roleId : roleIds){
            int addedRow = addRolePermission(permissionId, roleId);
            totalAdded +=addedRow;
        }
        return totalAdded;
    }
}
